﻿using System.Threading.Tasks;
using DailyPoetryX.Views;
using GalaSoft.MvvmLight.Messaging;
using Xamarin.Forms;

namespace DailyPoetryX.Services.Implementations {
    /// <summary>
    /// 根导航服务。
    /// </summary>
    public class RootNavigationService : IRootNavigationService {
        /******** 公开变量 ********/

        /******** 私有变量 ********/

        /// <summary>
        /// 根页面激活服务。
        /// </summary>
        private IRootPageActivationService rootPageActivationService;

        /// <summary>
        /// 导航工具。
        /// </summary>
        private MainPage MainPage =>
            _mainPage ?? (_mainPage = Application.Current.MainPage as MainPage);

        private MainPage _mainPage;

        /******** 继承方法 ********/

        /// <summary>
        /// 导航到页面。
        /// </summary>
        /// <param name="pageKey">页面键。</param>
        public async Task NavigateToAsync(string pageKey) {
            await MainPage.Detail.Navigation.PopToRootAsync();
            var page = rootPageActivationService.Activate(pageKey);
            MainPage.Detail = page;
            if (MainPage.MasterBehavior == MasterBehavior.Popover) {
                if (Device.RuntimePlatform == Device.Android) {
                    await Task.Delay(100);
                }

                MainPage.IsPresented = false;
            }

            Messenger.Default.Send(
                new RootNavigationMessage {PageKey = pageKey});
        }

        /// <summary>
        /// 导航到页面。
        /// </summary>
        /// <param name="pageKey">页面键。</param>
        /// <param name="parameter">参数。</param>
        public async Task NavigateToAsync(string pageKey, object parameter) {
            var page = rootPageActivationService.Activate(pageKey);
            await page.Navigation.PopToRootAsync();
            NavigationContext.SetParameter(page.CurrentPage, parameter);
            MainPage.Detail = page;
            if (MainPage.MasterBehavior == MasterBehavior.Popover) {
                if (Device.RuntimePlatform == Device.Android) {
                    await Task.Delay(100);
                }

                MainPage.IsPresented = false;
            }

            Messenger.Default.Send(
                new RootNavigationMessage {PageKey = pageKey});
        }

        /******** 公开方法 ********/

        public RootNavigationService(
            IRootPageActivationService rootPageActivationService) {
            this.rootPageActivationService = rootPageActivationService;
        }

        /******** 私有方法 ********/
    }
}